import { _decorator, Component, director, game, Node, Sprite, UITransform } from 'cc';
import { nodePool } from '../utils/nodePool';
import { gameConfig } from '../data/gameConfig';
import { emits } from '../data/enums';
import { red } from '../game/red';
import { LevelManager } from '../utils/LevelManager';
const { ccclass, property } = _decorator;

@ccclass('gameWindow')
export class gameWindow extends Component {
    private playerNode: Node
    @property(UITransform)
    mapSize: UITransform = null;
    //private playerPosition: number[]
    private LevelData: any;

    protected onLoad() {
        this.LevelData = LevelManager.Instance.getLevel(gameConfig.currentLevelNum);
        gameConfig.currentLevel = JSON.parse(JSON.stringify(this.LevelData.grid));
        director.on(emits.playerMove, this.playerSetPos, this);
        this.initMap();
        this.playerNode = nodePool.ins.getPoolNode("player", this.node);
        this.playerSetPos();
    }

    initMap() {
        gameConfig.redPoints = this.LevelData.redPositions;
        gameConfig.currentPos = this.LevelData.playerPosition;
        gameConfig.boxNodes = [];
        let mapArr = gameConfig.currentLevel;
        //地图大小设置
        this.mapSize.width = mapArr.length * gameConfig.blockSize;
        this.mapSize.height = mapArr[0].length * gameConfig.blockSize;
        //原点要重新设置
        gameConfig.gameOrigin = [(this.mapSize.width - gameConfig.blockSize) / 2, (this.mapSize.height - gameConfig.blockSize) / 2];
        let redArr = this.LevelData.redPositions;
        //先画红点
        for (let i = 0; i < redArr.length; i++) {
            let redNode = nodePool.ins.getPoolNode("red", this.node);
            let redTs: any = redNode.getComponent("red");
            redTs.position[0] = redArr[i][0];
            redTs.position[1] = redArr[i][1];
            redTs.init();
        }
        //再画箱子
        for (let i = 0; i < mapArr.length; i++) {
            for (let j = 0; j < mapArr[i].length; j++) {
                if (mapArr[i][j] == -1) {
                    //无箱子
                } else if (mapArr[i][j] == 0 || mapArr[i][j] == 1) {
                    let boxNode = nodePool.ins.getPoolNode("box", this.node);
                    let boxTs: any = boxNode.getComponent("box");
                    boxTs.position = [i, j];
                    boxTs.type = mapArr[i][j];
                    boxTs.init();
                    if (boxTs.type == 1) {
                        //存放可移动的箱子节点
                        gameConfig.boxNodes.push(boxNode);
                    }
                }
            }
        }
    }
    playerSetPos() {
        //坐标值*方块大小-游戏原点 设置左下角为[0,0]
        this.playerNode.setPosition(gameConfig.currentPos[0] * gameConfig.blockSize - gameConfig.gameOrigin[0], gameConfig.currentPos[1] * gameConfig.blockSize - gameConfig.gameOrigin[1]);
    }
}


